import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)

const router = new VueRouter({
  routes,
  // 始终滚动到顶部
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }
  }
})

// 因为编程时导航返回的是promise对象
// 重写push
// 先保存一份
let originPush = VueRouter.prototype.push
// 二次封装
VueRouter.prototype.push = function (location, resolve, reject) {
  // this指的是VueRouter的实例对象
  if (resolve && reject) {
    // 不用call方法this就指向window
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }
}
//重写replace方法
let originReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(this, location, () => { }, () => { })

  }
}

// 设置前置导航守卫
router.beforeEach(async (to, from, next) => {
  next()
  let token = store.state.registerStore.token
  let name = store.state.registerStore.userInfo.name
  // 已登录
  if (token) {
    if (to.path === '/login') {
      next('/home')
    } else {
      if (name) {
        next()
      } else {
        try {
          await store.dispatch('registerStore/getUserInfoByToken')
          next()
        } catch (error) {
          alert('身份过期！请重新登录！')
          await store.dispatch('registerStore/userLoginOut')
          next('/login')
        }
      }
    }
  } else {
    // 未登录
    if (to.path.indexOf('pay') !== -1 || to.path === '/shopcart' || to.path === '/trade' || to.path.indexOf('center') !== -1) {
      // 解析地址
      // 携带query路由可以直接指定用户登录跳转到哪里
      next('/login?redirect='+to.path)
    } else {
      next()
    }
  }
})


export default router